import json
import logging
import os
from typing import Optional

# 创建日志目录
LOG_DIR = os.getenv('LOG_DIR', '../logs')
os.makedirs(LOG_DIR, exist_ok=True)
from config.config import CONFIG

# 从环境变量获取日志配置

LOG_LEVEL = CONFIG.get('log_level') if CONFIG.get('log_level') else 'INFO'  # 日志级别
LOG_TO_FILE = CONFIG.get('log_level') if CONFIG.get('log_level') else False  # 是否记录到文件
LOG_FILE_PATH = CONFIG.get('log_file_path') if CONFIG.get('log_file_path') else os.path.join(LOG_DIR,
                                                                                             'app.log')  # 日志文件路径
LOG_JSON_FORMAT = CONFIG.get('LOG_JSON_FORMAT') if CONFIG.get('LOG_JSON_FORMAT') else False  # 是否使用JSON格式
from datetime import datetime

log_file_name = 'default'
logger = None


def configure_logger():
    """配置全局日志设置"""
    # 解析日志级别
    level = getattr(logging, LOG_LEVEL, logging.INFO)

    # 创建根日志记录器
    logger = logging.getLogger()
    logger.setLevel(level)

    # 移除已有的处理器，避免重复
    for handler in logger.handlers[:]:
        logger.removeHandler(handler)

    # 创建格式化器
    if LOG_JSON_FORMAT:
        formatter = JSONFormatter()
    else:
        format_str = '[%(asctime)s] [%(levelname)s] [%(module)s:%(lineno)d] %(message)s'
        formatter = logging.Formatter(format_str)

    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

    # 文件处理器
    if LOG_TO_FILE:
        caller_name = log_file_name
        log_file_path = os.path.join(LOG_DIR, f"{caller_name}.log")

        file_handler = logging.FileHandler(log_file_path)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

    return logger


def get_caller_module_name():
    """获取调用者的模块名，并附加当前日期"""
    # 添加当前日期
    current_date = datetime.now().strftime("%Y%m%d")
    return f"{log_file_name}_{current_date}"


class JSONFormatter(logging.Formatter):
    """JSON格式的日志格式化器"""

    def format(self, record):
        log_record = {
            'timestamp': self.formatTime(record),
            'level': record.levelname,
            'module': record.module,
            'line': record.lineno,
            'message': record.getMessage(),
            'exception': self.formatException(record.exc_info) if record.exc_info else None,
        }
        return json.dumps(log_record, ensure_ascii=False)


def get_logger(name: Optional[str] = None, file_name='app.log') -> logging.Logger:
    global log_file_name
    log_file_name = file_name
    # 配置全局logger
    global logger
    logger = configure_logger()
    """获取指定名称的日志记录器"""
    return logging.getLogger(name)


if __name__ == '__main__':
    logger = get_logger(__name__, '4444')
    logger.info('Hello, World!')
